<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简洁代码编辑器</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.1/min/vs/loader.js"></script>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            height: 100vh;
            overflow: hidden;
        }
        .container {
            display: flex;
            height: 100vh;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
        }
        .sidebar {
            width: 280px;
            background: #2c3e50;
            color: white;
            padding: 20px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
        }
        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            background: white;
        }
        .header {
            background: #3498db;
            color: white;
            padding: 15px 25px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        .editor-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }
        #editor {
            flex: 1;
            border: none;
        }
        .toolbar {
            background: #ecf0f1;
            padding: 12px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #bdc3c7;
        }
        .toolbar-left, .toolbar-right {
            display: flex;
            gap: 12px;
            align-items: center;
        }
        .btn {
            padding: 8px 16px;
            background: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 6px;
            transition: all 0.3s;
            font-size: 14px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        .btn:hover {
            background: #2980b9;
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.15);
        }
        .btn-success {
            background: #2ecc71;
        }
        .btn-success:hover {
            background: #27ae60;
        }
        .btn-danger {
            background: #e74c3c;
        }
        .btn-danger:hover {
            background: #c0392b;
        }
        .btn-warning {
            background: #f39c12;
        }
        .btn-warning:hover {
            background: #d35400;
        }
        .status {
            padding: 12px 20px;
            border-radius: 4px;
            display: none;
            margin: 10px 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        .success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        .breadcrumb {
                display: flex;
                align-items: center;
                padding: 10px;
                background: rgba(255, 255, 255, 0.05);
                border-radius: 6px;
                margin-bottom: 10px;
                font-size: 14px;
                overflow-x: auto;
                white-space: nowrap;
            }
            
            .breadcrumb-item {
                color: #3498db;
                cursor: pointer;
                padding: 4px 8px;
                border-radius: 3px;
                transition: background-color 0.2s;
            }
            
            .breadcrumb-item:hover {
                background-color: rgba(52, 152, 219, 0.1);
            }
            
            .breadcrumb-separator {
                color: #95a5a6;
                margin: 0 4px;
            }
            
            .file-list {
                margin-top: 20px;
                flex: 1;
                overflow-y: auto;
                border-radius: 6px;
                background: rgba(255, 255, 255, 0.05);
                padding: 10px;
            }
        .file-item {
                padding: 12px;
                margin-bottom: 8px;
                background: #34495e;
                border-radius: 6px;
                cursor: pointer;
                display: flex;
                justify-content: space-between;
                align-items: center;
                transition: all 0.3s;
                border-left: 3px solid transparent;
            }
            
            .file-item.directory {
                background: #2c3e50;
            }
            
            .file-item.directory:hover {
                background: #3d566e;
            }
        .file-item:hover {
            background: #3d566e;
            transform: translateX(5px);
            border-left: 3px solid #3498db;
        }
        .file-item.active {
            background: #3498db;
            border-left: 3px solid #2ecc71;
        }
        .file-actions {
            display: flex;
            gap: 8px;
        }
        .file-action {
            background: none;
            border: none;
            color: white;
            cursor: pointer;
            padding: 5px;
            border-radius: 3px;
            transition: background 0.3s;
        }
        .file-action:hover {
            background: rgba(255, 255, 255, 0.1);
        }
        .search-box {
            margin-top: 20px;
            position: relative;
        }
        .search-box input {
            width: 100%;
            padding: 10px 10px 10px 35px;
            border-radius: 6px;
            border: none;
            background: rgba(255, 255, 255, 0.1);
            color: white;
        }
        .search-box i {
            position: absolute;
            left: 10px;
            top: 50%;
            transform: translateY(-50%);
            color: #bdc3c7;
        }
        .file-info {
            margin-top: 20px;
            font-size: 0.85em;
            color: #bdc3c7;
            padding: 10px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 6px;
        }
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
            backdrop-filter: blur(3px);
        }
        .modal-content {
            background: white;
            padding: 25px;
            border-radius: 8px;
            width: 450px;
            max-width: 90%;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
            animation: modalFadeIn 0.3s;
        }
        @keyframes modalFadeIn {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        .modal-close {
            background: none;
            border: none;
            font-size: 1.5em;
            cursor: pointer;
            color: #7f8c8d;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #2c3e50;
        }
        .form-group input, .form-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            transition: border 0.3s;
        }
        .form-group input:focus, .form-group select:focus {
            border-color: #3498db;
            outline: none;
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
        }
        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 12px;
            margin-top: 20px;
        }
        .theme-selector, .language-selector {
            margin-top: 20px;
        }
        .theme-selector label, .language-selector label {
            display: block;
            margin-bottom: 8px;
            color: #ecf0f1;
            font-weight: bold;
        }
        .theme-selector select, .language-selector select {
            width: 100%;
            padding: 10px;
            border-radius: 4px;
            border: none;
            background: rgba(255, 255, 255, 0.15);
            color: white;
            font-size: 14px;
            cursor: pointer;
        }
        .theme-selector select option, .language-selector select option {
            background: #2c3e50;
            color: white;
            padding: 8px;
        }
        .file-icon {
            margin-right: 10px;
            width: 16px;
            text-align: center;
        }
        .directory {
            font-weight: bold;
        }
        .refresh-btn {
            background: none;
            border: none;
            color: white;
            cursor: pointer;
            padding: 5px;
            margin-left: 10px;
            border-radius: 3px;
            transition: background 0.3s;
        }
        .refresh-btn:hover {
            background: rgba(255, 255, 255, 0.1);
        }
        .file-size {
            font-size: 0.8em;
            color: #95a5a6;
            margin-left: 10px;
        }
        .sidebar-title {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding-bottom: 15px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        .logo {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .logo i {
            font-size: 1.5em;
            color: #3498db;
        }
        .empty-state {
            text-align: center;
            padding: 30px;
            color: #bdc3c7;
        }
        .empty-state i {
            font-size: 3em;
            margin-bottom: 15px;
            opacity: 0.5;
        }
        .error-state {
            text-align: center;
            padding: 30px;
            color: #e74c3c;
        }
        .error-state i {
            font-size: 3em;
            margin-bottom: 15px;
        }
        
        /* 工具栏中的语言选择器样式 */
        .toolbar .language-selector {
            margin-top: 0;
        }
        
        .toolbar .language-selector select {
            background: white;
            color: #333;
            border: 1px solid #bdc3c7;
            border-radius: 4px;
            padding: 6px 10px;
            font-size: 13px;
        }
        
        .toolbar .language-selector select option {
            background: white;
            color: #333;
        }
        
        .filename-hint {
            font-size: 0.8em;
            color: #95a5a6;
            margin-top: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="sidebar">
            <div class="sidebar-title">
                <div class="logo">
                    <i class="fas fa-code"></i>
                    <h2>文件浏览器</h2>
                </div>
                <button class="refresh-btn" id="refresh-files" title="刷新文件列表">
                    <i class="fas fa-sync-alt"></i>
                </button>
            </div>
            
            <div class="search-box">
                <i class="fas fa-search"></i>
                <input type="text" id="file-search" placeholder="搜索文件...">
            </div>
            
            <!-- 导航路径 -->
            <div class="breadcrumb" id="breadcrumb">
                <span class="breadcrumb-item" data-path="">/</span>
            </div>
            
            <div class="file-list" id="file-list">
                <div class="empty-state">
                    <i class="fas fa-spinner fa-spin"></i>
                    <p>加载中...</p>
                </div>
            </div>
            
            <div class="theme-selector">
                <label for="theme-select">编辑器主题:</label>
                <select id="theme-select">
                    <option value="vs">浅色主题</option>
                    <option value="vs-dark">深色主题</option>
                    <option value="hc-black">高对比度</option>
                </select>
            </div>
            
            <div class="file-info">
                <p><i class="fas fa-info-circle"></i> 双击文件进行编辑</p>
                <p><i class="fas fa-code"></i> 支持8.3格式文件名</p>
                <p><i class="fas fa-keyboard"></i> Ctrl+S 快速保存</p>
            </div>
        </div>
        
        <div class="main-content">
            <div class="header">
                <h1><i class="fas fa-laptop-code"></i> 简洁代码编辑器</h1>
                <div>
                    <span id="current-file">未选择文件</span>
                </div>
            </div>
            
            <div class="toolbar">
                <div class="toolbar-left">
                    <button class="btn" id="new-file-btn">
                        <i class="fas fa-file"></i> 新建文件
                    </button>
                    <button class="btn btn-success" id="save-btn">
                        <i class="fas fa-save"></i> 保存
                    </button>
                    <button class="btn btn-warning" id="run-btn">
                        <i class="fas fa-play"></i> 运行脚本
                    </button>
                    <button class="btn" id="upload-btn">
                        <i class="fas fa-upload"></i> 快速上传
                    </button>
                </div>
                <div class="toolbar-right">
                    <div class="language-selector">
                        <select id="language-select">
                            <option value="plaintext">纯文本</option>
                            <option value="javascript">JavaScript</option>
                            <option value="html">HTML</option>
                            <option value="css">CSS</option>
                            <option value="python">Python</option>
                            <option value="json">JSON</option>
                            <option value="markdown">Markdown</option>
                        </select>
                    </div>
                </div>
            </div>
            
            <div class="editor-container">
                <div id="editor"></div>
            </div>
            
            <div class="status" id="status-msg"></div>
        </div>
    </div>
    
    <!-- 新建文件模态框 -->
    <div class="modal" id="new-file-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3><i class="fas fa-file"></i> 新建文件</h3>
                <button class="modal-close" id="close-new-file-modal">&times;</button>
            </div>
            <div class="form-group">
                <label for="new-filename">文件名:</label>
                <input type="text" id="new-filename" placeholder="例如: SCRIPT.JS">
                <div class="filename-hint">系统将自动转换为8.3格式 (如: SCRIPT~1.JS)</div>
            </div>
            <div class="form-group">
                <label for="file-type">文件类型:</label>
                <select id="file-type">
                    <option value="">自动检测</option>
                    <option value=".JS">JavaScript (.JS)</option>
                    <option value=".HTM">HTML (.HTM)</option>
                    <option value=".CSS">CSS (.CSS)</option>
                    <option value=".PY">Python (.PY)</option>
                    <option value=".JSO">JSON (.JSO)</option>
                    <option value=".TXT">文本文件 (.TXT)</option>
                    <option value=".MD">Markdown (.MD)</option>
                </select>
            </div>
            <div class="modal-footer">
                <button class="btn" id="cancel-new-file">取消</button>
                <button class="btn btn-success" id="create-new-file">创建</button>
            </div>
        </div>
    </div>
    
    <!-- 删除确认模态框 -->
    <div class="modal" id="delete-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3><i class="fas fa-trash"></i> 确认删除</h3>
                <button class="modal-close" id="close-delete-modal">&times;</button>
            </div>
            <p>确定要删除文件 "<span id="delete-filename"></span>" 吗？此操作无法撤销。</p>
            <div class="modal-footer">
                <button class="btn" id="cancel-delete">取消</button>
                <button class="btn btn-danger" id="confirm-delete">删除</button>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化变量
            let editor;
            let currentFile = null;
            const CHUNK_SIZE = 1024;
            
            // 8.3格式扩展名映射
            const extensionMap = {
                // 标准扩展名映射
                'JS': 'javascript',
                'HTM': 'html',
                'HTML': 'html',
                'CSS': 'css',
                'PY': 'python',
                'JSO': 'json',
                'JSON': 'json',
                'TXT': 'plaintext',
                'MD': 'markdown',
                'XML': 'xml',
                'SQL': 'sql',
                'PHP': 'php',
                'C': 'c',
                'CPP': 'cpp',
                'H': 'c',
                'JAVA': 'java',
                'RB': 'ruby',
                'SH': 'shell',
                'BAT': 'bat',
                'PS1': 'powershell',
                'YML': 'yaml',
                'YAML': 'yaml',
                'INI': 'ini',
                'CFG': 'ini',
                'LOG': 'plaintext'
            };
            
            // DOM元素
            const statusMsg = document.getElementById('status-msg');
            const saveButton = document.getElementById('save-btn');
            const newFileButton = document.getElementById('new-file-btn');
            const runButton = document.getElementById('run-btn');
            const uploadButton = document.getElementById('upload-btn');
            const fileList = document.getElementById('file-list');
            const currentFileDisplay = document.getElementById('current-file');
            const themeSelect = document.getElementById('theme-select');
            const languageSelect = document.getElementById('language-select');
            const fileSearch = document.getElementById('file-search');
            const refreshFilesButton = document.getElementById('refresh-files');
            
            // 模态框元素
            const newFileModal = document.getElementById('new-file-modal');
            const deleteModal = document.getElementById('delete-modal');
            const newFilenameInput = document.getElementById('new-filename');
            const deleteFilenameSpan = document.getElementById('delete-filename');
            
            // 初始化Monaco编辑器
            require.config({ paths: { 'vs': 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.1/min/vs' }});
            require(['vs/editor/editor.main'], function() {
                editor = monaco.editor.create(document.getElementById('editor'), {
                    value: '', // 编辑器初始化为空
                    language: 'plaintext',
                    theme: 'vs',
                    automaticLayout: true,
                    fontSize: 14,
                    minimap: { enabled: true },
                    scrollBeyondLastLine: false,
                    wordWrap: 'on',
                    lineNumbers: 'on',
                    folding: true,
                    renderWhitespace: 'selection',
                    formatOnPaste: true,
                    formatOnType: true
                });
                
                // 加载文件列表（根目录）
                loadFileList('');
            });
            
            // 刷新文件列表按钮事件
            refreshFilesButton.addEventListener('click', function() {
                loadFileList(currentPath);
            });
            
            // 显示状态消息
            function showStatus(message, type) {
                statusMsg.textContent = message;
                statusMsg.className = 'status ' + type;
                statusMsg.style.display = 'block';
                
                // 5秒后自动隐藏
                setTimeout(() => {
                    statusMsg.style.display = 'none';
                }, 5000);
            }
            
            // 当前路径变量
            let currentPath = '';
            
            // 获取文件列表
            async function loadFileList(path = '') {
                // 先更新currentPath变量
                currentPath = path;
                
                try {
                    fileList.innerHTML = '<div class="loading-state"><i class="fas fa-spinner fa-spin"></i><p>加载中...</p></div>';
                    
                    // 更新导航路径显示
                    updateBreadcrumb(path);
                    
                    // 使用POST请求/api/list端点来获取文件列表
                    const response = await fetch('/api/list', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ path: path }) // 传入指定路径
                    });
                    
                    if (!response.ok) {
                        throw new Error(`服务器返回错误: ${response.status} ${response.statusText}`);
                    }
                    
                    // 解析JSON响应
                    const filesData = await response.json();
                    
                    // 转换数据格式以适应renderFileList函数
                    const files = filesData.map(file => ({
                        name: file.name,
                        type: file.isDirectory ? 'directory' : 'file',
                        icon: file.isDirectory ? 'fas fa-folder' : getFileIcon(file.name),
                        size: file.size
                    }));
                    
                    if (files.length === 0) {
                        fileList.innerHTML = '<div class="empty-state"><i class="fas fa-folder-open"></i><p>目录为空</p></div>';
                        showStatus('目录为空', 'info');
                    } else {
                        renderFileList(files);
                        showStatus(`已加载 ${files.length} 个文件`, 'success');
                    }
                    
                } catch (error) {
                    console.error('加载文件列表失败:', error);
                    fileList.innerHTML = `<div class="error-state">
                        <i class="fas fa-exclamation-triangle"></i>
                        <p>加载文件列表失败</p>
                        <p style="font-size: 0.8em; margin-top: 10px;">${error.message}</p>
                        <button class="btn" onclick="location.reload()" style="margin-top: 15px; background: #e74c3c;">
                            <i class="fas fa-redo"></i> 重新加载
                        </button>
                    </div>`;
                    showStatus('加载文件列表失败: ' + error.message, 'error');
                }
            }
            
            // 解析文件列表文本
            function parseFileList(text) {
                const files = [];
                
                // 如果文本包含HTML标签，说明不是纯文件列表
                if (text.includes('<') && text.includes('>')) {
                    throw new Error('服务器返回HTML内容而不是文件列表');
                }
                
                // 简单的解析逻辑 - 按行分割并过滤空行
                const lines = text.split('\n').filter(line => line.trim());
                
                lines.forEach(line => {
                    const trimmedLine = line.trim();
                    
                    // 跳过明显的HTML标签或特殊内容
                    if (trimmedLine.startsWith('<') || 
                        trimmedLine.includes('<!DOCTYPE') || 
                        trimmedLine.includes('<html') ||
                        trimmedLine.includes('HTTP') ||
                        trimmedLine.length > 100) {
                        return;
                    }
                    
                    // 简单的判断：如果包含点号可能是文件，否则可能是目录
                    if (trimmedLine.includes('.')) {
                        files.push({
                            name: trimmedLine,
                            type: 'file',
                            icon: getFileIcon(trimmedLine)
                        });
                    } else if (trimmedLine) {
                        files.push({
                            name: trimmedLine,
                            type: 'directory',
                            icon: 'fas fa-folder'
                        });
                    }
                });
                
                return files;
            }
            
            // 根据文件扩展名获取图标（支持8.3格式）
            function getFileIcon(filename) {
                // 从路径中提取文件名
                const basename = filename.split('/').pop();
                const ext = getFileExtension(basename).toUpperCase();
                switch(ext) {
                    case 'JS': return 'fas fa-file-code';
                    case 'HTM': return 'fas fa-file-code';
                    case 'HTML': return 'fas fa-file-code';
                    case 'CSS': return 'fas fa-file-code';
                    case 'PY': return 'fas fa-file-code';
                    case 'JSO': return 'fas fa-file-code';
                    case 'JSON': return 'fas fa-file-code';
                    case 'MD': return 'fas fa-file-alt';
                    case 'TXT': return 'fas fa-file-alt';
                    default: return 'fas fa-file';
                }
            }
            
            // 格式化文件大小显示
            function formatFileSize(bytes) {
                if (bytes === 0) return '0 B';
                
                const k = 1024;
                const sizes = ['B', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                const validIndex = Math.min(i, sizes.length - 1);
                
                return parseFloat((bytes / Math.pow(k, validIndex)).toFixed(2)) + ' ' + sizes[validIndex];
            }
            
            // 获取文件扩展名（支持8.3格式）
            function getFileExtension(filename) {
                // 从路径中提取文件名
                const basename = filename.split('/').pop();
                const parts = basename.split('.');
                return parts.length > 1 ? parts[parts.length - 1] : '';
            }
            
            // 根据8.3格式扩展名设置语言
            function setLanguageByExtension(filename) {
                // 从路径中提取文件名
                const basename = filename.split('/').pop();
                const extension = getFileExtension(basename).toUpperCase();
                let language = extensionMap[extension] || 'plaintext';
                
                monaco.editor.setModelLanguage(editor.getModel(), language);
                languageSelect.value = language;
            }
            
            // 渲染文件列表
            function renderFileList(files) {
                if (files.length === 0) {
                    fileList.innerHTML = '<div class="empty-state"><i class="fas fa-folder-open"></i><p>目录为空</p></div>';
                    return;
                }
                
                fileList.innerHTML = '';
                
                files.forEach(file => {
                    const fileItem = document.createElement('div');
                    fileItem.className = `file-item ${file.type === 'directory' ? 'directory' : ''}`;
                    
                    // 格式化文件大小显示
                    const fileSizeText = file.size !== undefined ? formatFileSize(file.size) : '';
                    
                    fileItem.innerHTML = `
                        <div>
                            <i class="${file.icon} file-icon"></i>
                            ${file.name}
                            ${fileSizeText ? `<span class="file-size">${fileSizeText}</span>` : ''}
                        </div>
                        ${file.type === 'file' ? `
                        <div class="file-actions">
                            <button class="file-action edit-file" data-filename="${file.name}" title="编辑">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="file-action delete-file" data-filename="${file.name}" title="删除">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                        ` : ''}
                    `;
                    fileList.appendChild(fileItem);
                    
                    if (file.type === 'file') {
                        // 添加双击编辑事件
                        fileItem.addEventListener('dblclick', () => {
                            openFile(file.name);
                        });
                        
                        // 添加编辑按钮事件
                        fileItem.querySelector('.edit-file').addEventListener('click', (e) => {
                            e.stopPropagation();
                            openFile(file.name);
                        });
                        
                        // 添加删除按钮事件
                        fileItem.querySelector('.delete-file').addEventListener('click', (e) => {
                            e.stopPropagation();
                            showDeleteModal(file.name);
                        });
                    } else if (file.type === 'directory') {
                        // 为目录添加点击事件
                    fileItem.addEventListener('click', () => {
                        // 构建新路径并加载新目录的文件列表
                        const newPath = currentPath ? `${currentPath}/${file.name}` : file.name;
                        loadFileList(newPath);
                    });
                    } else {
                        fileItem.style.cursor = 'default';
                        fileItem.querySelector('.file-icon').style.color = '#f39c12';
                    }
                });
            }
            
            // 更新导航路径
            function updateBreadcrumb(path) {
                const breadcrumb = document.getElementById('breadcrumb');
                breadcrumb.innerHTML = '<span class="breadcrumb-item" data-path="">/</span>';
                
                if (!path) return;
                
                const parts = path.split('/');
                let currentPath = '';
                
                parts.forEach((part, index) => {
                    if (part) {
                        currentPath += (index === 0 ? '' : '/') + part;
                        const breadcrumbItem = document.createElement('span');
                        breadcrumbItem.className = 'breadcrumb-separator';
                        breadcrumbItem.textContent = '/';
                        breadcrumb.appendChild(breadcrumbItem);
                        
                        const item = document.createElement('span');
                        item.className = 'breadcrumb-item';
                        item.textContent = part;
                        item.dataset.path = currentPath;
                        breadcrumb.appendChild(item);
                        
                        // 添加点击事件
                        item.addEventListener('click', () => {
                            loadFileList(item.dataset.path);
                        });
                    }
                });
            }
            
            // 为导航路径项添加事件监听
            document.addEventListener('click', function(e) {
                if (e.target.classList.contains('breadcrumb-item')) {
                    const path = e.target.dataset.path;
                    loadFileList(path);
                }
            });
            
            // 创建空白文件
            function createEmptyFile(filename) {
                // 对于保存文件，filename已经是完整路径，但需要确保格式正确
                let fullPath = filename;
                // 如果只是文件名（没有路径分隔符）并且在某个目录中，则构建完整路径
                if (!filename.includes('/') && currentPath) {
                    fullPath = `${currentPath}/${filename}`;
                }
                // 移除开头的斜杠（如果有），因为后端会移除
                if (fullPath.startsWith('/')) {
                    fullPath = fullPath.substring(1);
                }
                return fetch('/api/create', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ filename: fullPath })
                }).then(response => response.json());
            }
            
            // 追加内容到文件
            function appendToFile(filename, content) {
                // 对于保存文件，filename已经是完整路径，但需要确保格式正确
                let fullPath = filename;
                // 如果只是文件名（没有路径分隔符）并且在某个目录中，则构建完整路径
                if (!filename.includes('/') && currentPath) {
                    fullPath = `${currentPath}/${filename}`;
                }
                // 移除开头的斜杠（如果有），因为后端会移除
                if (fullPath.startsWith('/')) {
                    fullPath = fullPath.substring(1);
                }
                return fetch('/api/append', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 
                        filename: fullPath,
                        content: content 
                    })
                }).then(response => response.json());
            }
            
            // 快速上传整个文件
            function uploadFile(filename, content) {
                // 确保使用完整路径，但移除开头的斜杠（后端会处理）
                let fullPath = filename;
                if (!filename.includes('/') && currentPath) {
                    fullPath = `${currentPath}/${filename}`;
                }
                // 移除开头的斜杠（如果有），因为后端会移除
                if (fullPath.startsWith('/')) {
                    fullPath = fullPath.substring(1);
                }
                return fetch('/api/upload', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 
                        filename: fullPath,
                        content: content 
                    })
                }).then(response => response.json());
            }
            
            // 获取文件内容
            function getFileContent(filename) {
                // 确保使用完整路径
                const filePath = filename.startsWith('/') ? filename : `/${filename}`;
                return fetch(filePath)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('文件不存在或无法访问');
                        }
                        return response.text();
                    });
            }
            
            // 删除文件
            function deleteFile(filename) {
                // 构建完整路径
                const fullPath = currentPath ? `${currentPath}/${filename}` : filename;
                return fetch('/api/remove', {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ filename: fullPath })
                }).then(response => response.json());
            }
            
            // 执行脚本
            function executeScript(path) {
                // 确保使用完整路径
                let fullPath = path;
                if (!path.includes('/') && currentPath) {
                    fullPath = `${currentPath}/${path}`;
                }
                // 移除开头的斜杠（如果有），因为后端会移除
                if (fullPath.startsWith('/')) {
                    fullPath = fullPath.substring(1);
                }
                
                console.log('执行脚本路径:', fullPath);
                
                return new Promise((resolve, reject) => {
                    fetch('/api/sensors', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ path: fullPath })
                    })
                    .then(response => {
                        console.log('响应状态:', response.status);
                        
                        // 检查响应是否有效
                        if (!response.ok) {
                            throw new Error(`HTTP错误! 状态: ${response.status}`);
                        }
                        
                        // 直接获取文本响应
                        return response.text();
                    })
                    .then(text => {
                        // 确保text不为null或undefined
                        const responseText = text ? text.trim() : '';
                        console.log('原始响应文本:', responseText);
                        
                        try {
                            // 检查是否为错误消息
                            if (responseText.startsWith('ERR')) {
                                resolve({ status: 'error', message: responseText, raw: responseText });
                                return;
                            }
                            
                            // 尝试解析为JSON
                            try {
                                const jsonResponse = JSON.parse(responseText);
                                // 确保返回一个有效的对象
                                const result = typeof jsonResponse === 'object' && jsonResponse !== null ? jsonResponse : {};
                                if (result.status === undefined) {
                                    result.status = 'success';
                                }
                                result.raw = responseText;
                                resolve(result);
                            } catch (jsonError) {
                                // 尝试解析为数字（更宽松的检查）
                                const cleanText = responseText.replace(/^"|"$/g, ''); // 去除可能的引号
                                if (!isNaN(cleanText) && cleanText !== '') {
                                    const numValue = parseFloat(cleanText);
                                    resolve({ status: 'success', value: numValue, message: cleanText, raw: responseText });
                                } else {
                                    // 如果既不是有效JSON也不是数字，将其作为成功响应返回
                                    resolve({ status: 'success', message: responseText, raw: responseText });
                                }
                            }
                        } catch (e) {
                            console.error('响应处理错误:', e);
                            // 兜底处理，确保总是返回有效响应
                            resolve({ status: 'success', message: responseText || '无响应内容', raw: responseText });
                        }
                    })
                    .catch(error => {
                        console.error('API请求错误:', error);
                        // 转换为resolve而不是reject，确保调用者能够处理错误
                        resolve({ status: 'error', message: error.message || '未知请求错误', raw: error.message });
                    });
                });
            }
            
            // 分段保存文件
            async function saveFileInChunks(filename, content) {
                // 确保filename已经包含完整路径，因为currentFile已经是完整路径
                // 首先创建空白文件
                const createResult = await createEmptyFile(filename);
                if (createResult.status !== 'success') {
                    throw new Error(`创建文件失败: ${createResult.message}`);
                }
                
                // 如果内容为空，直接返回成功
                if (!content) {
                    return { bytesWritten: 0 };
                }
                
                let totalBytesWritten = 0;
                
                // 分段追加内容
                for (let i = 0; i < content.length; i += CHUNK_SIZE) {
                    const chunk = content.substring(i, i + CHUNK_SIZE);
                    const appendResult = await appendToFile(filename, chunk);
                    
                    if (appendResult.status !== 'success') {
                        throw new Error(`追加内容失败: ${appendResult.message}`);
                    }
                    
                    totalBytesWritten += appendResult.bytesWritten;
                }
                
                return { bytesWritten: totalBytesWritten };
            }
            
            // 打开文件
            async function openFile(filename) {
                // 构建完整路径
                const fullPath = currentPath ? `${currentPath}/${filename}` : filename;
                try {
                    const content = await getFileContent(fullPath);
                    editor.setValue(content);
                    currentFile = fullPath;
                    currentFileDisplay.textContent = filename;
                    
                    // 根据文件扩展名设置语言（支持8.3格式）
                    setLanguageByExtension(filename);
                    
                    // 更新文件列表中的活动状态
                    document.querySelectorAll('.file-item').forEach(item => {
                        item.classList.remove('active');
                        const itemName = item.querySelector('div').textContent.trim();
                        if (itemName === filename) {
                            item.classList.add('active');
                        }
                    });
                    
                    showStatus(`已打开文件: ${fullPath}`, 'success');
                } catch (error) {
                    showStatus(`打开文件失败: ${error.message}`, 'error');
                }
            }
            
            // 保存文件
            saveButton.addEventListener('click', async function() {
                if (!currentFile) {
                    showStatus('请先选择或创建一个文件', 'error');
                    return;
                }
                
                const content = editor.getValue();
                
                // 显示加载状态
                saveButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';
                saveButton.disabled = true;
                
                try {
                    // 使用分段保存函数
                    const result = await saveFileInChunks(currentFile, content);
                    showStatus(`文件保存成功: ${currentFile} (${result.bytesWritten} 字节)`, 'success');
                } catch (error) {
                    showStatus(`保存失败: ${error.message}`, 'error');
                } finally {
                    saveButton.innerHTML = '<i class="fas fa-save"></i> 保存';
                    saveButton.disabled = false;
                }
            });
            
            // 快速上传
            uploadButton.addEventListener('click', async function() {
                if (!currentFile) {
                    showStatus('请先选择或创建一个文件', 'error');
                    return;
                }
                
                const content = editor.getValue();
                
                // 显示加载状态
                uploadButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 上传中...';
                uploadButton.disabled = true;
                
                try {
                    const result = await uploadFile(currentFile, content);
                    if (result.status === 'success') {
                        showStatus(`文件上传成功: ${currentFile}`, 'success');
                    } else {
                        throw new Error(result.message);
                    }
                } catch (error) {
                    showStatus(`上传失败: ${error.message}`, 'error');
                } finally {
                    uploadButton.innerHTML = '<i class="fas fa-upload"></i> 快速上传';
                    uploadButton.disabled = false;
                }
            });
            
            // 新建文件
            newFileButton.addEventListener('click', function() {
                newFilenameInput.value = '';
                document.getElementById('file-type').value = '';
                newFileModal.style.display = 'flex';
                newFilenameInput.focus();
            });
            
            // 确保结果显示区域在DOM加载时就创建
            function initResultDisplay() {
                // 在页面加载时就创建结果显示区域
                const resultDisplay = document.createElement('div');
                resultDisplay.id = 'result-display';
                resultDisplay.style.cssText = `
                    background: #f8f9fa;
                    border: 1px solid #dee2e6;
                    border-radius: 4px;
                    padding: 15px;
                    margin: 15px;
                    max-height: 400px;
                    min-height: 150px;
                    overflow-y: auto;
                    font-family: monospace;
                    font-size: 14px;
                    display: none;
                    z-index: 100;
                    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
                    transition: all 0.3s ease;
                `;
                
                // 确保editor-container存在再添加
                const editorContainer = document.querySelector('.editor-container');
                if (editorContainer) {
                    editorContainer.appendChild(resultDisplay);
                    console.log('结果显示区域已创建');
                } else {
                    console.warn('editor-container不存在，将结果显示区域添加到body');
                    document.body.appendChild(resultDisplay);
                }
            }
            
            // 立即初始化结果显示区域
            initResultDisplay();
            
            // 获取结果显示区域
            function getResultDisplay() {
                let resultDisplay = document.getElementById('result-display');
                if (!resultDisplay) {
                    // 兜底创建
                    initResultDisplay();
                    resultDisplay = document.getElementById('result-display');
                }
                return resultDisplay;
            }
            
            // 显示执行结果
            function showExecutionResult(result) {
                console.log('显示执行结果:', result);
                const resultDisplay = getResultDisplay();
                
                // 确保result是一个对象
                const safeResult = typeof result === 'object' && result !== null ? result : { status: 'error', message: '无效的响应对象' };
                let resultHTML = '';
                
                if (safeResult.status === 'success') {
                    // 根据结果类型显示不同的内容
                    if (safeResult.value !== undefined) {
                        // 数字类型结果
                        resultHTML = `<div style="color: #28a745;">执行结果: ${safeResult.value}</div>`;
                    } else if (safeResult.message !== undefined) {
                        // 文本类型结果
                        resultHTML = `<div style="color: #28a745;">执行结果: ${safeResult.message}</div>`;
                    } else if (safeResult.raw) {
                        // 使用原始内容
                        resultHTML = `<div style="color: #28a745;">执行结果:</div>
                            <pre style="margin: 10px 0; color: #333;">${safeResult.raw}</pre>`;
                    } else {
                        // 兜底
                        resultHTML = `<div style="color: #28a745;">执行成功，但无返回内容</div>`;
                    }
                } else {
                    // 错误结果
                    resultHTML = `<div style="color: #dc3545;">错误: ${safeResult.message || '未知错误'}</div>`;
                    if (safeResult.raw) {
                        resultHTML += `<pre style="margin: 10px 0; color: #666; font-size: 12px;">原始错误: ${safeResult.raw}</pre>`;
                    }
                }
                
                // 添加执行时间戳
                const timestamp = new Date().toLocaleTimeString();
                resultHTML = `<div style="font-size: 12px; color: #666; margin-bottom: 10px;">执行时间: ${timestamp}</div>` + resultHTML;
                
                resultDisplay.innerHTML = resultHTML;
                
                // 强制显示
                resultDisplay.style.display = 'block';
                resultDisplay.style.visibility = 'visible';
                resultDisplay.style.opacity = '1';
                
                // 滚动到结果区域
                resultDisplay.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            }
            
            // 运行文件
            runButton.addEventListener('click', async function() {
                if (!currentFile) {
                    showStatus('请先选择或创建一个文件', 'error');
                    return;
                }
                
                // 清除之前的结果显示
                const resultDisplay = getResultDisplay();
                resultDisplay.innerHTML = '<div style="text-align: center; color: #666;"><i class="fas fa-spinner fa-spin"></i> 执行中...</div>';
                resultDisplay.style.display = 'block';
                
                try {
                    showStatus(`正在执行脚本: ${currentFile}`, 'info');
                    
                    // 直接使用executeScript的结果（它已经返回resolve而不是reject）
                    const result = await executeScript(currentFile);
                    
                    // 添加详细调试信息
                    console.log('脚本执行响应:', JSON.stringify(result));
                    
                    // 现在result总是一个对象
                    if (result && result.status === 'success') {
                        showStatus(`脚本执行成功: ${currentFile}`, 'success');
                    } else {
                        // 错误处理
                        const errorMessage = result && result.message ? result.message : '未知错误';
                        showStatus(`执行失败: ${errorMessage}`, 'error');
                    }
                    
                    // 无论成功失败都显示结果
                    showExecutionResult(result);
                    
                } catch (error) {
                    // 这个catch现在应该很少被触发，因为executeScript已经处理了错误
                    console.error('运行按钮事件处理错误:', error);
                    showStatus(`执行失败: ${error.message || '未知错误'}`, 'error');
                    showExecutionResult({ 
                        status: 'error', 
                        message: error.message || '未知错误',
                        raw: String(error)
                    });
                }
            });
            
            // 主题切换
            themeSelect.addEventListener('change', function() {
                monaco.editor.setTheme(this.value);
            });
            
            // 语言切换
            languageSelect.addEventListener('change', function() {
                monaco.editor.setModelLanguage(editor.getModel(), this.value);
            });
            
            // 文件搜索
            fileSearch.addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase();
                const fileItems = document.querySelectorAll('.file-item');
                
                fileItems.forEach(item => {
                    const filename = item.querySelector('div').textContent.toLowerCase();
                    if (filename.includes(searchTerm)) {
                        item.style.display = 'flex';
                    } else {
                        item.style.display = 'none';
                    }
                });
            });
            
            // 刷新文件列表
            refreshFilesButton.addEventListener('click', function() {
                loadFileList(currentPath);
                showStatus('文件列表已刷新', 'info');
            });
            
            // 新建文件模态框事件
            document.getElementById('close-new-file-modal').addEventListener('click', function() {
                newFileModal.style.display = 'none';
            });
            
            document.getElementById('cancel-new-file').addEventListener('click', function() {
                newFileModal.style.display = 'none';
            });
            
            document.getElementById('create-new-file').addEventListener('click', async function() {
                let filename = newFilenameInput.value.trim().toUpperCase();
                const fileType = document.getElementById('file-type').value;
                
                if (!filename) {
                    showStatus('请输入文件名', 'error');
                    return;
                }
                
                // 如果选择了文件类型，确保文件名有正确的扩展名
                if (fileType && !filename.toUpperCase().endsWith(fileType)) {
                    filename += fileType;
                }
                
                try {
                    await createEmptyFile(filename);
                    newFileModal.style.display = 'none';
                    showStatus(`文件创建成功: ${filename}`, 'success');
                    
                    // 打开新创建的文件
                    openFile(filename);
                    
                    // 重新加载文件列表
                    loadFileList(currentPath);
                } catch (error) {
                    showStatus(`创建文件失败: ${error.message}`, 'error');
                }
            });
            
            // 删除文件模态框事件
            function showDeleteModal(filename) {
                deleteFilenameSpan.textContent = filename;
                deleteModal.style.display = 'flex';
                
                // 设置删除确认事件
                document.getElementById('confirm-delete').onclick = async function() {
                    try {
                        await deleteFile(filename);
                        deleteModal.style.display = 'none';
                        showStatus(`文件删除成功: ${filename}`, 'success');
                        
                        // 如果删除的是当前打开的文件，清空编辑器
                        if (currentFile === filename) {
                            editor.setValue('');
                            currentFile = null;
                            currentFileDisplay.textContent = '未选择文件';
                        }
                        
                        // 重新加载文件列表
                        loadFileList(currentPath);
                    } catch (error) {
                        showStatus(`删除文件失败: ${error.message}`, 'error');
                    }
                };
            }
            
            document.getElementById('close-delete-modal').addEventListener('click', function() {
                deleteModal.style.display = 'none';
            });
            
            document.getElementById('cancel-delete').addEventListener('click', function() {
                deleteModal.style.display = 'none';
            });
            
            // 点击模态框外部关闭
            window.addEventListener('click', function(event) {
                if (event.target === newFileModal) {
                    newFileModal.style.display = 'none';
                }
                if (event.target === deleteModal) {
                    deleteModal.style.display = 'none';
                }
            });
            
            // 键盘快捷键
            document.addEventListener('keydown', function(e) {
                if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                    e.preventDefault();
                    saveButton.click();
                }
            });
        });
    </script>
</body>
</html>